package cz.cvut.manatee.processManager;

import java.util.HashMap;
import java.util.Map;
import com.phrasebox.manatee.*;

public class OptimizedConcordance {
	
	private static class ConcordanceMapContent {
		private final Concordance concordance;
		private final Corpus corpus;
		private final String cql;
		
		public ConcordanceMapContent(Concordance concordance, Corpus corpus, String cql) {
			this.concordance = concordance;
			this.corpus      = corpus;
			this.cql         = cql;
		}
		
		public Concordance getConcordance() {
			return this.concordance;
		}
		
		public boolean equal(String other) {
			return this.cql.equalsIgnoreCase(other);
		}
		
		public boolean equal(Corpus other) {
			return (this.corpus == other);
		}
	}
	
	private static Map<ThreadRunnable, ConcordanceMapContent> instances = new HashMap<ThreadRunnable, ConcordanceMapContent>();

	public static Concordance getInstance(ThreadRunnable thread, Corpus corp, String cql) {
		if (OptimizedConcordance.instances.containsKey(thread)) {
			// vlakno je jiz registrovano - jiz drive pozadovalo konkordanci
			ConcordanceMapContent saved = OptimizedConcordance.instances.get(thread);
			if (saved != null) {
				if (saved.equal(cql) && saved.equal(corp)) {
					// v mape byl ulozen stejny korpus
					System.out.println("OptimConc: zadost o CQL, jiz existuje. Vytvoreno: "+OptimizedConcordance.instances.size());
					return saved.getConcordance();
				}
			}
		}
		
		System.out.println("OptimConc: zadost o CQL, jdu tvorit novou. Zatim vytvoreno: "+OptimizedConcordance.instances.size());
		// vlakno zada poprve nebo vlakno obsahovalo jinou konkordanci
		Concordance conc = new Concordance(corp, cql, 0);
		OptimizedConcordance.instances.put(thread, new ConcordanceMapContent(conc, corp, cql));
		return conc;
	}
	
	public static void reset() {
		OptimizedConcordance.instances.clear();
	}
}
